package com.example.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/*
 **@Author:youpeng
 **Created on 2022/4/9
 */
@Service
public class VerifyServiceImpl implements VerifyService{

    @Resource
    JavaMailSender sender;
    @Resource
    StringRedisTemplate template;
    @Value("${spring.mail.username}")
    String form;

    @Override
    public void sendVerifyCode(String email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("[xxx网站] 你的注册验证码");
        Random random = new Random();
        int code = random.nextInt(899999) + 100000;
        template.opsForValue().set("verify:code:"+email,code+"",3, TimeUnit.MINUTES);
        message.setText("你的注册验证码为："+code+",三分钟有效");
        message.setTo(email);
        message.setFrom(form);
        sender.send(message);
    }

    @Override
    public boolean doVerify(String email, String code) {
        String s = template.opsForValue().get("verify:code:" + email);
        if (s==null) return false;
        if(!s.equals(code)) return false;
        template.delete("verify:code:" + email);
        return true;
    }
}
